/***********************************************
 This file is part of redia-lib-utils-ios
.
 
 Copyright (c) 2014 Redia A/S
 
 Redia-library-app-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-library-app-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-library-app-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

#import "UrlCacheVideoEntry.h"
#import "UrlCacheManager.h"
#import "defines.h"

@implementation UrlCacheVideoEntry


-(BOOL)loadVideoFromUrl:(NSURL *)inURL delegate:(id<UrlCacheEntryDelegate>)finishedDelegate
{
    self.fetchFromUrl = inURL;
	self.delegate = finishedDelegate;
	
	NSURLRequest *request = [NSURLRequest requestWithURL:inURL];
    self.urlConnection = [NSURLConnection connectionWithRequest:request delegate:self];
	
    if (self.urlConnection) {
        self.videoLocalFilePath = [self pathForTemporaryFileWithPrefix:@"video-cache"];
        outputFile =  [[NSOutputStream alloc] initToFileAtPath:self.videoLocalFilePath append:NO];
        [outputFile setDelegate:self];
        [outputFile open];

    } else {
        return FALSE;
    }
	
    return TRUE;
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	NSLog(@"UrlCacheEntry load video error: %@",error);
    NSLog(@"error url: %@",self.fetchFromUrl);
	[self.delegate cacheEntry:self didFailOnUrl:self.fetchFromUrl error:error];
}

- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response {
	if ([response respondsToSelector:@selector(statusCode)])
	{
		int statusCode = (int)[((NSHTTPURLResponse *)response) statusCode];
		if (statusCode >= 400)
		{
			[conn cancel];  // stop connecting; no more delegate messages
			NSDictionary *errorInfo
			= [NSDictionary dictionaryWithObject:[NSString stringWithFormat:
												  NSLocalizedString(@"Server returned status code %d",@""),
												  statusCode]
										  forKey:NSLocalizedDescriptionKey];
			NSError *statusError
			= [NSError errorWithDomain:NSURLErrorDomain
								  code:statusCode
							  userInfo:errorInfo];
			[self connection:conn didFailWithError:statusError];
		}
	}
    self.receivedLength=0;
    self.expectedFileSize = [response expectedContentLength];
}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data {
    [outputFile write:[data bytes] maxLength:[data length]];
    self.receivedLength += [data length];
    
    float completed = ((double) self.receivedLength)/((double)self.expectedFileSize);
    //DLog(@"completed: %lf", completed);
    
    if (self.delegate!=nil && [self.delegate respondsToSelector:@selector(progress:)]) {
        [self.delegate progress:completed];
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn {
    // do something with the data
    DLog(@"UrlCacheEntry video load received %lld bytes of data", self.receivedLength);
	
    [outputFile close];
    if (self.receivedLength>0) {
        //only insert into cache if any data was received
        self.videoLocalFilePath = [[UrlCacheManager instance] saveVideoFromTempFilePath:self.videoLocalFilePath fromUrl:self.fetchFromUrl expireTime:7258118400]; //in 200 years
        [self.delegate cacheEntry:self didLoadObjectFromUrl:self.fetchFromUrl ofType:UrlCacheEntryTypeVideo];
	} else {
        [self.delegate cacheEntry:self didFailOnUrl:self.fetchFromUrl error:[NSError errorWithDomain:@"UrlCacheVideoEntry" code:99 userInfo:@{NSLocalizedDescriptionKey: @"Received 0 data bytes for video"}]];
    }

}

- (NSString *)pathForTemporaryFileWithPrefix:(NSString *)prefix
{
    NSString *  result;
    CFUUIDRef   uuid;
    CFStringRef uuidStr;
    
    uuid = CFUUIDCreate(NULL);
    assert(uuid != NULL);
    
    uuidStr = CFUUIDCreateString(NULL, uuid);
    assert(uuidStr != NULL);
    
    result = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-%@", prefix, uuidStr]];
    assert(result != nil);
    
    CFRelease(uuidStr);
    CFRelease(uuid);
    
    return result;
}

- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
    DLog(@"event code: %lu",(long)eventCode);
}


@end
